import path from "path";
import fs from "fs";

function queryControllers(controllersDir) {
  //拿到controllers的绝对路径
  let controllerDir = path.resolve("./") + "/" + controllersDir;
  //判断controllers的路径是否存在
  if (fs.existsSync(controllerDir)) {
    //拿到所有controllers包下的所有文件
    let queryAllCtrlFile = fs.readdirSync(controllersDir);
    //过滤并拼接可被浏览器解析的完整路由js路径
    let allCtrlJs = queryAllCtrlFile
      .filter((file) => file.endsWith(".js"))
      .map((file) => `file:///${controllerDir}/${file}`);
    //返回已过滤并拼接且可被浏览器解析的完整路由js路径
    return allCtrlJs;
  }

  //路径不存在返回null
  return null;
}

function regiRoute(router, controllersPath) {
  controllersPath.forEach(async (file) => {
    let { users } = await import(file);
    for (const user in users) {
      //解构请求方式及请求路径
      const [reqMethod, reqPath] = user.split(" ");
      //拿出请求所对应的方法
      const reqFn = users[user];
      if (reqMethod === "get") {
        router.get(reqPath, reqFn);
      }
      if (reqMethod === "post") {
        router.post(reqPath, reqFn);
      }
      if (reqMethod === "delete") {
        router.delete(reqPath, reqFn);
      }
      if (reqMethod === "put") {
        router.put(reqPath, reqFn);
      }
    }
  });
}

export const regRoute = regiRoute;
export const queryAllControllers = queryControllers;
